package cn.itcast.bos.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.base.CourierRepository;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.service.CourierService;

@Service
@Transactional
public class CourierServiceImpl implements CourierService {

	@Autowired
	private CourierRepository courierRepository;

	@Override
	public void save(Courier courier) {
		courierRepository.save(courier);
	}

	@Override
	public Page<Courier> findAll(Pageable pageable) {

		return courierRepository.findAll(pageable);
	}

	public Page<Courier> findAll2(Specification<Courier> specification,
			Pageable pageable) {

		return courierRepository.findAll(specification, pageable);

	}

	@Override
	public void delBatch(String[] str) {
		
		List<Integer> list = new ArrayList<Integer>();
		for(int i=0;i<str.length;i++){
			list.add(Integer.parseInt(str[i],10));
		}
		courierRepository.delBatch(list);
		
	}
	/*
	 * @Override public void delBatch(String[] str) {
	 * 
	 * for(String strs:str){ courierRepository.delBatch(Integer.parseInt(strs));
	 * } }
	 */

	
	// 关联快递员
	@Override
	public List<Courier> findNoassociation() {
		
		Specification<Courier> specification = new Specification<Courier>(){

			@Override
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				
				// 这里查询的未关联过定区的快递员，所以这里是idEmpty
				// 直接去表中查询所有fixedAreas为空的数据，所以不需要传参
				// bean中写属性，因为前台要用到，但是数据库中是没有的
				Predicate p1 = cb.isEmpty(root.get("fixedAreas").as(Set.class));
				
				return p1;
			}};
		return courierRepository.findAll(specification);
		
		
	}

}
